package core;

import java.util.Hashtable;

import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.Queue;
import javax.jms.QueueConnection;
import javax.jms.QueueConnectionFactory;
import javax.jms.QueueReceiver;
import javax.jms.QueueSession;
import javax.jms.Session;
import javax.jms.TextMessage;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;

public class Receive implements MessageListener {

	// Inicialização do serviço Receive
	private IMessageReader reader;
	private QueueConnection queueConnection;
	private QueueSession queueSession;
	private Queue queue;
	private QueueReceiver queueReceiver;
	
	public Receive(IMessageReader reader) {
		this.reader = reader;
	}

	public void inicia(String endereco, String canal) {
		try {
			// create a JNDI context
			Hashtable<String, String> properties = new Hashtable<String, String>();
			properties.put(Context.INITIAL_CONTEXT_FACTORY,	"org.exolab.jms.jndi.InitialContextFactory");
			properties.put(Context.PROVIDER_URL, "tcp://" + endereco + "/");
			Context context = new InitialContext(properties);

			// retrieve queue connection factory
			QueueConnectionFactory queueConnectionFactory = (QueueConnectionFactory) context.lookup("JmsQueueConnectionFactory");
			// create a queue connection
			queueConnection = queueConnectionFactory.createQueueConnection();

			/* 
			 * create a queue session set transactions to false 
			 * and set auto acknowledgement of receipt of messages
			 */ 
			queueSession = queueConnection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);

			// retrieve queue
			queue = (Queue) context.lookup(canal);

			// create a queue receiver and associate to the retrieved queue
			queueReceiver = queueSession.createReceiver(queue);

			// associate message listener
			queueReceiver.setMessageListener(this);

			// start delivery of incoming messages
			queueConnection.start();
			
		} catch (NamingException e) {
			e.printStackTrace();
		} catch (JMSException e) {
			e.printStackTrace();
		}
	}

	@Override
	public void onMessage(Message message) {
		try {
			String messageText = null;
			if (message instanceof TextMessage){
				messageText = ((TextMessage) message).getText();
				this.reader.readMessage(messageText);
			}
		
		} catch (JMSException e) {
			e.printStackTrace();
		}
	}

}
